import React, { useState } from 'react';
import { Modal, Input, Button, message, List, Avatar, Alert, Spin, Space, Divider } from 'antd';
import { ImportOutlined, CheckOutlined, CloseOutlined, GlobalOutlined } from '@ant-design/icons';
import { fetchWebsiteInfo, getBasicWebsiteInfo, importMultipleWebsites } from '../utils/websiteImporter';

const { TextArea } = Input;

const WebsiteImporter = ({ visible, onCancel, onImport }) => {
  const [urls, setUrls] = useState('');
  const [loading, setLoading] = useState(false);
  const [previewData, setPreviewData] = useState([]);
  const [errors, setErrors] = useState([]);
  const [useAdvanced, setUseAdvanced] = useState(false);

  const handlePreview = async () => {
    if (!urls.trim()) {
      message.warning('请输入网站URL');
      return;
    }

    setLoading(true);
    setPreviewData([]);
    setErrors([]);

    try {
      const urlList = urls.split(',').map(url => url.trim()).filter(url => url);
      
      if (urlList.length === 0) {
        message.warning('请输入有效的URL');
        return;
      }

      if (useAdvanced) {
        // 使用高级模式（需要网络请求）
        const { results, errors: importErrors } = await importMultipleWebsites(urlList);
        setPreviewData(results);
        setErrors(importErrors);
      } else {
        // 使用基础模式（本地解析）
        const results = [];
        const errors = [];
        
        for (const url of urlList) {
          try {
            const websiteInfo = getBasicWebsiteInfo(url);
            results.push(websiteInfo);
          } catch (error) {
            errors.push({ url, error: error.message });
          }
        }
        
        setPreviewData(results);
        setErrors(errors);
      }
    } catch (error) {
      message.error('解析失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const handleImport = () => {
    if (previewData.length === 0) {
      message.warning('没有可导入的网站');
      return;
    }

    onImport(previewData);
    handleReset();
  };

  const handleReset = () => {
    setUrls('');
    setPreviewData([]);
    setErrors([]);
    setUseAdvanced(false);
  };

  const handleCancel = () => {
    handleReset();
    onCancel();
  };

  return (
    <Modal
      title={
        <Space>
          <ImportOutlined />
          批量导入网站
        </Space>
      }
      open={visible}
      onCancel={handleCancel}
      width={800}
      footer={[
        <Button key="cancel" onClick={handleCancel}>
          取消
        </Button>,
        <Button key="reset" onClick={handleReset}>
          重置
        </Button>,
        <Button 
          key="preview" 
          type="default" 
          onClick={handlePreview}
          loading={loading}
        >
          解析预览
        </Button>,
        <Button 
          key="import" 
          type="primary" 
          onClick={handleImport}
          disabled={previewData.length === 0}
        >
          导入网站 ({previewData.length})
        </Button>
      ]}
    >
      <div style={{ marginBottom: '16px' }}>
        <Alert
          message="批量导入说明"
          description={
            <div>
              <p>• 输入影视网站的URL地址，多个网址用英文逗号分隔</p>
              <p>• 系统会自动解析网站名称、图标和搜索地址</p>
              <p>• 支持的格式：https://example.com 或 example.com</p>
              <p>• 示例：https://movie.douban.com, https://www.imdb.com</p>
            </div>
          }
          type="info"
          showIcon
          style={{ marginBottom: '16px' }}
        />
      </div>      <div
 style={{ marginBottom: '16px' }}>
        <TextArea
          placeholder="请输入网站URL，多个网址用英文逗号分隔&#10;例如：https://movie.douban.com, https://www.imdb.com, https://gimy.ai"
          value={urls}
          onChange={(e) => setUrls(e.target.value)}
          rows={4}
          style={{ marginBottom: '12px' }}
        />
        
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <Button
              type={useAdvanced ? 'primary' : 'default'}
              size="small"
              onClick={() => setUseAdvanced(!useAdvanced)}
            >
              {useAdvanced ? '高级模式' : '基础模式'}
            </Button>
            <span style={{ marginLeft: '8px', fontSize: '12px', color: '#666' }}>
              {useAdvanced ? '自动获取网站标题和图标' : '基于URL生成基础信息'}
            </span>
          </div>
        </div>
      </div>

      {loading && (
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <Spin size="large" tip="正在解析网站信息..." />
        </div>
      )}

      {previewData.length > 0 && (
        <div style={{ marginBottom: '16px' }}>
          <Divider orientation="left">
            <Space>
              <CheckOutlined style={{ color: '#52c41a' }} />
              成功解析 ({previewData.length})
            </Space>
          </Divider>
          <List
            dataSource={previewData}
            renderItem={(item, index) => (
              <List.Item>
                <List.Item.Meta
                  avatar={
                    <Avatar 
                      src={item.icon} 
                      icon={<GlobalOutlined />}
                      style={{ backgroundColor: '#f0f0f0' }}
                    />
                  }
                  title={
                    <div>
                      <strong>{item.name}</strong>
                      <span style={{ marginLeft: '8px', fontSize: '12px', color: '#999' }}>
                        #{index + 1}
                      </span>
                    </div>
                  }
                  description={
                    <div>
                      <div style={{ marginBottom: '4px' }}>
                        <span style={{ color: '#666' }}>网址：</span>
                        <a href={item.url} target="_blank" rel="noopener noreferrer">
                          {item.url}
                        </a>
                      </div>
                      <div style={{ fontSize: '12px', color: '#999' }}>
                        搜索：{item.searchUrl}
                      </div>
                    </div>
                  }
                />
              </List.Item>
            )}
            style={{ 
              maxHeight: '300px', 
              overflowY: 'auto',
              border: '1px solid #f0f0f0',
              borderRadius: '6px',
              padding: '8px'
            }}
          />
        </div>
      )}

      {errors.length > 0 && (
        <div>
          <Divider orientation="left">
            <Space>
              <CloseOutlined style={{ color: '#ff4d4f' }} />
              解析失败 ({errors.length})
            </Space>
          </Divider>
          <List
            dataSource={errors}
            renderItem={(error) => (
              <List.Item>
                <Alert
                  message={error.url}
                  description={error.error}
                  type="error"
                  showIcon
                  style={{ width: '100%' }}
                />
              </List.Item>
            )}
            style={{ 
              maxHeight: '200px', 
              overflowY: 'auto'
            }}
          />
        </div>
      )}
    </Modal>
  );
};

export default WebsiteImporter;